<template>
  <div>
    <el-dialog    title="修改餐品信息"   :visible.sync="isShow"  width="500px"  @close="closeDialog" >
      <el-form  :model="mealForm"  :rules="rules"  ref="ruleForm"  label-width="100px"   class="demo-ruleForm" >
        <el-form-item label="餐品名称" prop="mname">
          <el-input  v-model="mealForm.mname"   placeholder="请输入餐品名称" clearable ></el-input>
        </el-form-item>
        <el-form-item label="餐品单价" prop="price">
          <el-input  v-model="mealForm.price"   placeholder="请输入餐品单价" type="number"  min="0"  step="0.01"  ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">确定</el-button>
          <el-button @click="closeDialog">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: 'MealInfo',
  props: {
    isShow:Boolean,
    mealInfo: Object
  },
  data() {
    return {
      mealForm: {
        mid: 0,
        mname: '',
        price: '',
        isavaliable:1
      },
      rules: {
        mname: [
          { required: true, message: '请输入餐品名称', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入餐品单价', trigger: 'blur' },
          { 
            validator: (rule, value, callback) => {
              if (value && parseFloat(value) < 0) {
                callback(new Error('单价不能为负数'));
              } else {
                callback();
              }
            }, 
            trigger: 'blur' 
          }
        ]
      }
    }
  },
  methods: {
    closeDialog() {
      this.mealForm = {
        mid: 0,
        mname: '',
        price: '',
        isavaliable:1
      }
      this.$refs['ruleForm'].resetFields();
      this.$emit('closeDialog')
    },
    submitForm() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          let url = this.mealForm.mid != 0 ? '/updateMeal' : '/addMeal'
          this.$http.post(url, this.mealForm).then(res => {
            if (res.data === 'success') {
              this.$emit('mealSave', res.data)
            } else {
              this.$message.error("操作失败，请重试！")
            }
          })
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    }
  },
  watch: {
    isShow(val) {
      this.dialogFormVisible = val
    },
    mealInfo: {
      handler(val) {
        //数据拷贝到表单
        this.mealForm = { ...val }
      },
      //初始化立刻执行
      immediate: true
    }
  }
}
</script>
<style scoped>
.demo-ruleForm {
  margin-top: 20px;
}
.el-form-item {
  margin-bottom: 25px;
}
</style>